import 'dart:io';

import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../../components/update_app/check_app_version.dart';
import '../../../routes/route_name.dart';
import '../../../config/app_env.dart' show appEnv;
import 'provider/counterStore.p.dart';

class Home extends StatefulWidget {
  const Home({super.key, this.params});
  final dynamic params;

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  late CounterStore _counter;
  FocusNode blankNode = FocusNode(); // 响应空白处的焦点的Node

  @override
  Widget build(BuildContext context) {
   // checkNetworkPermissions();

    super.build(context);
    _counter = Provider.of<CounterStore>(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('home页面'),
        automaticallyImplyLeading: false,
      ),
      body: GestureDetector(
        onTap: () {
          // 点击空白页面关闭键盘
          FocusScope.of(context).requestFocus(blankNode);
        },
        child: contextWidget(),
      ),
    );
  }

  Widget contextWidget() {
    return ListView(
      children: List.generate(1, (index) {
        return Column(
          children: <Widget>[
            Text('App渠道：${appEnv.getAppChannel()}'),
            _button(
              '跳转test页',
              onPressed: () {
                Navigator.pushNamed(
                  context,
                  RouteName.testDemo,
                  arguments: {'data': '别名路由传参666'},
                );
              },
            ),
            Text('状态管理值：${context.watch<CounterStore>().value}'),
            _button(
              '加+',
              onPressed: () {
                _counter.increment();
              },
            ),
            _button(
              '减-',
              onPressed: () {
                _counter.decrement();
              },
            ),
            _button(
              '强制更新App',
              onPressed: () {
                checkAppVersion(forceUpdate: true);
              },

            ),
            _button(
              'GPS测试页',
              onPressed: () {
                Navigator.pushNamed(
                  context,
                  RouteName.gpsTestDemo,
                  arguments: {'data': '别名路由传参666'},
                );
              },

            ),
            SimpleElevatedButton(
              color: Colors.blue,
              onPressed: () {
                Navigator.pushNamed(
                  context,
                  RouteName.backgroundTestDemo,
                  arguments: {'data': 'backgroundTestDemo'},
                );
              },
              child: const Text('组件 Button',style: TextStyle(color:Colors.white),),
            ),
            // SimpleElevatedButton(
            //   color: Colors.blue,
            //   onPressed: () {
            //     Navigator.pushNamed(
            //       context,
            //       RouteName.gaodeDemo,
            //       arguments: {'data': 'backgroundTestDemo'},
            //     );
            //   },
            //   child: const Text('高德测试',style: TextStyle(color:Colors.white),),
            // ),
          ],
        );
      }),
    );
  }

  Widget _button(String text, {VoidCallback? onPressed}) {
    return Container(
      margin: const EdgeInsets.only(top: 10),
      child: ElevatedButton(
        onPressed: onPressed,
        child: Text(
          text,
          style: TextStyle(fontSize: 22.sp),
        ),
      ),
    );
  }


  Future<bool> checkPermission() async {
    const permission = Permission.bluetooth;

    if (await permission.isDenied || await permission.isRestricted) {
      // 用户以前拒绝了权限请求或权限被限制
      if (await permission.request().isDenied) {
        // 用户永久拒绝了权限请求
        return false;
      }
    }

    // 用户已授权或用户同意授权
    return true;
  }

  Future<void> checkNetworkPermissions() async {
    final PackageInfo packageInfo = await PackageInfo.fromPlatform();
    final String packageName = packageInfo.packageName;

    // 检查权限
    final bool hasPermission = await checkPermission();

    if (!hasPermission) {
      // 权限未被授予，您可以引导用户前往设置页面手动开启
      throw Exception('No network permission granted for $packageName');
    }
  }
}

class SimpleElevatedButton extends StatelessWidget {
  const SimpleElevatedButton(
      {this.child,
        this.color,
        this.onPressed,
        this.borderRadius = 6,
        this.padding = const EdgeInsets.symmetric(horizontal: 28, vertical: 20),
        super.key});
  final Color? color;
  final Widget? child;
  final Function? onPressed;
  final double borderRadius;
  final EdgeInsetsGeometry padding;

  @override
  Widget build(BuildContext context) {
    ThemeData currentTheme = Theme.of(context);
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        padding: padding, backgroundColor: color ?? currentTheme.primaryColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(borderRadius),
        ),
      ),
      onPressed: onPressed as void Function()?,
      child: child,
    );
  }
}

